package com.example.shardingjdbcdemo.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @describte:自定义分片
 * @program:sharding-jdbc-demo
 * @author:zhengdp
 * @create:2021-09-25 18:20:37
 **/
public class MySharding implements PreciseShardingAlgorithm<String> {
    /**
     *
     * @param collection 实际的表名
     * @param preciseShardingValue 包含逻辑表名+参与分片的列名+值
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        String orderId = preciseShardingValue.getValue();
        int mode = orderId.hashCode()%collection.size();
        mode = Math.abs(mode);
        String[] actualTables = collection.toArray(new String[0]);
        System.out.println("mode = "+mode);
        return actualTables[mode];
    }
}
